﻿using System;
using System.Linq;

using Spencen.Mobile.Markup;
using Spencen.Mobile.Markup.Extensions;
using Spencen.Mobile.UI.Templating;

namespace Spencen.Mobile.UI.Markup.Extensions
{
    public class TemplateBinding : Binding
    {
        public TemplateBinding( object target, string propertyName ) : base( target, propertyName )
        {
        }

        public override object GetValue( XamlNode context, object parentInstance )
        {
            // Don't use the supplied context - instead we move upwards till we find the DataTemplate
            var templateNode = FindNodeForType( context, typeof(IDataTemplate) );
            if ( templateNode != null )
            {
                Target = templateNode.DataContext;
                return Value;
            }
            return null;
        }

        private static XamlNode FindNodeForType( XamlNode startingNode, Type type )
        {
            var element = startingNode as XamlElement;
            if ( element != null )
                if ( type.IsAssignableFrom( element.Type ) )
                    return element;
            if ( startingNode.Parent != null )
                return FindNodeForType( startingNode.Parent, type );
            return null;
        }
    }
}
